import random,time,requests,json

# from db import db
from model.models import db
from flask import Blueprint, request, jsonify, send_file, redirect
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r
from utils.sms import send_message, get_ali_object
from utils.myjwt import myjwt
from model.models import *

vip_dp = Blueprint('vip_dp', __name__)

api = Api(vip_dp)

# 充值vip
@vip_dp.route("/buy",methods=['POST'])
def getviplist():
    data = json.loads(request.data)
    userid = data["userid"]
    year = data["year"]
    money = 200
    tmoney = money * int(year)
    order_no = str(int(time.time()))+str(userid)
    vip = VipRecord(userid=userid,year=year,money=tmoney,active_money=tmoney,status=1,order_no=order_no)
    db.session.add(vip)
    db.session.commit()
    # 支付
    alipay = get_ali_object()
    order_no=order_no +","+str(1)
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买vip服务",  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    # 支付宝网关地址（沙箱应用）
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(
        query_params)
    pkey = 'orderpayfail'
    r.sortedset_add(pkey, order_no, int(time.time()))
    return jsonify({"code": 200, 'url': pay_url})

@vip_dp.route("/callback")
def callback():
    data = request.args
    datames = {k:v for k,v in data.items()}
    #删除字典中key为sign的记录
    sign = datames.pop('sign')
    #鉴权
    pay = get_ali_object()
    flag = pay.verify(datames,sign)
    if flag == True:
        #订单号
        order_no = datames["out_trade_no"]
        order_no_index = order_no.split(",")
        #支付宝流水号
        transaction_no = datames["trade_no"]
        #事务处理
        try:
            if order_no_index[1] == 1:
                #订单号更新vip订单表
                record = VipRecord.query.filter(VipRecord.order_no==order_no).first()
                record.status=2
                record.transaction_no=transaction_no
                db.session.add(record)
                #更新用户表
                user_info = User.query.filter(User.id==record.userid).first()
                user_info.level = 2
                print(user_info.id)
                #更新vip表
                vip = Vip.query.filter(Vip.userid==record.userid,status=1).first()
                if vip is not None:
                    #结束时间+购买年限
                    etime = vip.e_time.split("-")
                    year = int(etime[0])+int(record.year)
                    vip.e_time = year
                    print(">>><<<")
                else:
                    nowyear = datetime.date.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
                    etime = nowyear.split("-")
                    year = int(etime[0])+int(record.year)
                    print(year)
                    str1 = "-"
                    retime = str1.join(etime)
                    print(retime,">>>")
                    vip = Vip(userid=record.userid,s_time=datetime.datetime.now(),e_time=retime)
                    db.session.add(vip)
                    print("<<<>>>")
                db.session.commit()
            if order_no_index[1] == 2:
                # 订单号更新订单表
                record = Orders.query.filter(Orders.number == order_no).first()
                record.status = 3
                db.session.add(record)
                db.session.commit()
        except:
            db.session.rollback()
    else:
        print("鉴权失败")
    return redirect('http://localhost:8080/#/')